package com.ncu.music_notification;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.RemoteViews;

import static java.lang.System.exit;

public class MainActivity extends AppCompatActivity {

    private NotificationManager notificationManager;
    private NotificationChannel mChannel;
    private int NOTE_ID = 11;
    private String Channer_Name = "MUSIC_CHANNEL";
    private String Channer_ID = "MUSIC_CHANNEL_ONE";
    private String Channel_Description = "MUSIC_PLAYER_CHANNEL";
    private String noteTitle = "Music Play";
    private String noteMessage = "";
    private NotificationManager notifManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //取消当前所有Notification
        NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notifManager.cancelAll();
        //关闭服务
        Intent musicSvc = new Intent(this, MusicServer.class);
        stopService(musicSvc);
        //创建通知频道
        createChannel();
        MusicFragment frag_music = new MusicFragment(this);
        getSupportFragmentManager().beginTransaction().replace(
                R.id.container, frag_music).commit();
    }

    //重载系统返回按钮处理
    @Override
    public void onBackPressed() {
        onStop();
    }

    @Override
    protected void onStop() {
        super.onStop();
        confirmExitRunning();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //创建通知频道
    public void createChannel() {
        NotificationCompat.Builder builder;
        if (notifManager == null) {
            notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //将通知重用性设为低，这样就不会有通知的声音(部分模拟器仍然会发声)
                int importance = NotificationManager.IMPORTANCE_LOW;
                mChannel = notifManager.getNotificationChannel(Channer_ID);
                if (mChannel == null) {
                    mChannel = new NotificationChannel(Channer_ID, Channer_Name, importance);
                    mChannel.setDescription(Channel_Description);
                    notifManager.createNotificationChannel(mChannel);
                }
            }
        }
    }

    //该函数设置通知栏的视图内容，包括布局和布局内四个按钮的点击事件处理
    public RemoteViews getRemoteView() {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification);
        remoteViews.setTextViewText(R.id.tv_msg, noteMessage);
        //播放按钮打开服务
        Intent intent = new Intent(this, MusicServer.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
        remoteViews.setOnClickPendingIntent(R.id.btn_play, pendingIntent);
        //停止按钮打开服务(设置停止标签)
        Intent stopIntent = new Intent(this, MusicServer.class);
        stopIntent.setAction("STOP");
        PendingIntent pendingStop = PendingIntent.getService(this, 0, stopIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.btn_pause, pendingStop);
        //关闭按钮打开广捆
        Intent closeIntent = new Intent(this, CloseNotificationReceiver.class);
        PendingIntent bpi = PendingIntent.getBroadcast(this, 0, closeIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.btn_close, bpi);
        //打开App按钮打开MainActivity
        Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
                0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.iv_icon, pi);
        return remoteViews;
    }

    //创建并显示通知
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void createNotification() {
        Intent intent = new Intent(this, MusicServer.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
            //由于只有一首固定的曲 子为例，所以这里就把乐曲名称固定写在这里
            //如果是实际音乐播放，这里应该是根据当前音乐名称动态更新的
        noteMessage = "music.mp3";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            //使用Notification ompat而不是Notification,因为Notification需要API 16才能使用
            //NotificationCompat存在于V4 Support Library
            NotificationCompat.Builder compatbuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(noteTitle)
                    .setContentText(noteMessage)
                    .setAutoCancel(false) // 不会自动消失
                    .setOngoing(true)
                //无法通过滑动移除的通知
                    .setWhen(System.currentTimeMillis())
                    .setContentIntent(pendingIntent);
            if (compatbuilder != null) {
                //设置通知栏的视图内容
                compatbuilder.setContent(getRemoteView());
                notifManager.notify(NOTE_ID, compatbuilder.build());
            } else {
                Notification.Builder notificationBuilder =
                        new Notification.Builder(getApplicationContext(), Channer_ID)
                                .setSmallIcon(R.drawable.ic_music_video_black_24dp)
                                .setContentTitle(noteTitle)
                                .setContentText(noteMessage)
                                .setAutoCancel(false) // 不会自动消失
                                .setOngoing(true)
                                //无法通过滑动移除的通知
                                .setWhen(System.currentTimeMillis())
                                .setContentIntent(pendingIntent);
                if (notificationBuilder != null) {
                    notificationBuilder.setContent(getRemoteView());
                    notificationManager.notify(NOTE_ID, notificationBuilder.build());
                }
            }
        }
    }
    //退出程序时询问是否要启动后台运行
    public void confirmExitRunning(){
        new AlertDialog.Builder(MainActivity.this)
                .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("退出提示")
                .setMessage("要在后台运行吗? ")
                .setPositiveButton("后台运行", new DialogInterface.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    createNotification();
                    Intent musicSvc = new Intent(getApplicationContext(), MusicServer.class);
                    stopService(musicSvc); // 关闭服务
                    exit(0);
        }
    })
    .setNegativeButton("直接退出", new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int whichButton) {
            Intent musicSvc = new Intent(getApplicationContext(), MusicServer.class);
            stopService(musicSvc); // 关闭服务
            exit(0);
        }
        }).create().show();
    }
    //内部广播类
    public static class CloseNotificationReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancelAll();
            Intent musicSvc = new Intent(context,MusicServer.class);
            context.stopService(musicSvc);
        }
    }
}

